/**
 * 弹幕测试场景
 * 提供多种测试场景来验证弹幕系统的性能和功能
 */

import type { DetectionArea } from '../types'

export interface TestScenario {
  name: string
  description: string
  duration: number // 持续时间(秒)
  generateAreas: (timestamp: number) => DetectionArea[]
}

/**
 * 静态场景：单个固定人脸
 */
export const staticSingleFace: TestScenario = {
  name: '静态单人',
  description: '视频中央有一个固定的人脸区域',
  duration: 30,
  generateAreas: (_timestamp: number) => [
    {
      left: 200,
      top: 150,
      right: 400,
      bottom: 350
    }
  ]
}

/**
 * 静态场景：多个固定人脸
 */
export const staticMultipleFaces: TestScenario = {
  name: '静态多人',
  description: '视频中有多个固定的人脸区域',
  duration: 30,
  generateAreas: (_timestamp: number) => [
    {
      left: 100,
      top: 100,
      right: 250,
      bottom: 250
    },
    {
      left: 350,
      top: 150,
      right: 500,
      bottom: 300
    },
    {
      left: 200,
      top: 300,
      right: 350,
      bottom: 450
    }
  ]
}

/**
 * 动态场景：水平移动的人脸
 */
export const horizontalMovement: TestScenario = {
  name: '水平移动',
  description: '人脸从左到右水平移动',
  duration: 20,
  generateAreas: (timestamp: number) => {
    const progress = (timestamp % 20000) / 20000 // 20秒循环
    const x = 50 + progress * 500 // 从50px移动到550px
    
    return [{
      left: x,
      top: 200,
      right: x + 150,
      bottom: 350
    }]
  }
}

/**
 * 动态场景：垂直移动的人脸
 */
export const verticalMovement: TestScenario = {
  name: '垂直移动',
  description: '人脸从上到下垂直移动',
  duration: 15,
  generateAreas: (timestamp: number) => {
    const progress = (timestamp % 15000) / 15000 // 15秒循环
    const y = 50 + progress * 400 // 从50px移动到450px
    
    return [{
      left: 250,
      top: y,
      right: 400,
      bottom: y + 150
    }]
  }
}

/**
 * 动态场景：快速运动
 */
export const rapidMovement: TestScenario = {
  name: '快速运动',
  description: '人脸快速不规则移动，测试性能',
  duration: 10,
  generateAreas: (timestamp: number) => {
    const t = timestamp / 1000 // 转换为秒
    const x = 300 + Math.sin(t * 3) * 200 // 快速正弦波移动
    const y = 250 + Math.cos(t * 2) * 150 // 快速余弦波移动
    
    return [{
      left: x - 75,
      top: y - 75,
      right: x + 75,
      bottom: y + 75
    }]
  }
}

/**
 * 动态场景：多人快速运动
 */
export const multipleRapidMovement: TestScenario = {
  name: '多人快速运动',
  description: '多个人脸同时快速移动，压力测试',
  duration: 15,
  generateAreas: (timestamp: number) => {
    const t = timestamp / 1000
    const areas: DetectionArea[] = []
    
    // 三个快速移动的人脸
    for (let i = 0; i < 3; i++) {
      const phase = i * Math.PI * 2 / 3 // 120度相位差
      const x = 300 + Math.sin(t * 2 + phase) * 150
      const y = 250 + Math.cos(t * 1.5 + phase) * 100
      
      areas.push({
        left: x - 60,
        top: y - 60,
        right: x + 60,
        bottom: y + 60
      })
    }
    
    return areas
  }
}

/**
 * 边界场景：人脸在边缘
 */
export const edgeDetection: TestScenario = {
  name: '边缘检测',
  description: '人脸在视频边缘，测试边界处理',
  duration: 20,
  generateAreas: (timestamp: number) => {
    const t = timestamp / 1000
    const progress = (t % 20) / 20 // 20秒循环
    
    // 沿着视频边缘移动
    let x, y
    if (progress < 0.25) {
      // 顶边：左到右
      x = progress * 4 * 600
      y = 0
    } else if (progress < 0.5) {
      // 右边：上到下
      x = 600
      y = (progress - 0.25) * 4 * 400
    } else if (progress < 0.75) {
      // 底边：右到左
      x = 600 - (progress - 0.5) * 4 * 600
      y = 400
    } else {
      // 左边：下到上
      x = 0
      y = 400 - (progress - 0.75) * 4 * 400
    }
    
    return [{
      left: Math.max(0, x - 50),
      top: Math.max(0, y - 50),
      right: Math.min(600, x + 50),
      bottom: Math.min(400, y + 50)
    }]
  }
}

/**
 * 压力场景：大量人脸
 */
export const stressTest: TestScenario = {
  name: '压力测试',
  description: '大量人脸同时出现，测试系统极限',
  duration: 10,
  generateAreas: (timestamp: number) => {
    const areas: DetectionArea[] = []
    const t = timestamp / 1000
    
    // 生成9个人脸（3x3网格）
    for (let row = 0; row < 3; row++) {
      for (let col = 0; col < 3; col++) {
        const baseX = 100 + col * 200
        const baseY = 80 + row * 120
        
        // 添加轻微的随机移动
        const x = baseX + Math.sin(t + row + col) * 20
        const y = baseY + Math.cos(t + row + col) * 15
        
        areas.push({
          left: x - 40,
          top: y - 40,
          right: x + 40,
          bottom: y + 40
        })
      }
    }
    
    return areas
  }
}

/**
 * 所有测试场景
 */
export const allTestScenarios: TestScenario[] = [
  staticSingleFace,
  staticMultipleFaces,
  horizontalMovement,
  verticalMovement,
  rapidMovement,
  multipleRapidMovement,
  edgeDetection,
  stressTest
]

/**
 * 测试场景管理器
 */
export class TestScenarioManager {
  private currentScenario: TestScenario | null = null
  private startTime = 0
  private onUpdate?: (areas: DetectionArea[]) => void

  constructor(onUpdate?: (areas: DetectionArea[]) => void) {
    this.onUpdate = onUpdate
  }

  /**
   * 开始测试场景
   */
  startScenario(scenario: TestScenario): void {
    this.currentScenario = scenario
    this.startTime = Date.now()
    // console.log(`🎬 开始测试场景: ${scenario.name}`)
    // console.log(`📝 描述: ${scenario.description}`)
    // console.log(`⏱️ 持续时间: ${scenario.duration}秒`)
  }

  /**
   * 停止当前场景
   */
  stopScenario(): void {
    if (this.currentScenario) {
      // console.log(`⏹️ 停止测试场景: ${this.currentScenario.name}`)
      this.currentScenario = null
      this.onUpdate?.([])
    }
  }

  /**
   * 更新场景（在渲染循环中调用）
   */
  update(): DetectionArea[] {
    if (!this.currentScenario) {
      return []
    }

    const elapsed = Date.now() - this.startTime
    
    // 检查是否超时
    if (elapsed > this.currentScenario.duration * 1000) {
      // console.log(`✅ 测试场景完成: ${this.currentScenario.name}`)
      this.currentScenario = null
      return []
    }

    // 生成当前时间的检测区域
    const areas = this.currentScenario.generateAreas(elapsed)
    this.onUpdate?.(areas)
    
    return areas
  }

  /**
   * 获取当前场景信息
   */
  getCurrentScenario(): TestScenario | null {
    return this.currentScenario
  }

  /**
   * 获取场景进度 (0-1)
   */
  getProgress(): number {
    if (!this.currentScenario) {
      return 0
    }

    const elapsed = Date.now() - this.startTime
    return Math.min(1, elapsed / (this.currentScenario.duration * 1000))
  }
}
